package com.spontaneappnew;

import java.util.ArrayList;
import java.util.Collections;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.spontaneappnew.activities.AbstractNavDrawerActivity;
import com.spontaneappnew.activities.HomeActivity;
import com.spontaneappnew.activities.MyPlacesNew;
import com.spontaneappnew.activities.PlaceProfileActivity;
import com.spontaneappnew.activities.SettingsActivity;
import com.spontaneappnew.adapters.NavDrawerAdapter;

public class SurpriseMeActivity extends AbstractNavDrawerActivity implements OnClickListener, AnimationListener {
	
	private ArrayList<Place> randomPlaces;
	private int currIndex;
	private ImageView category;
	private TextView placeName, address, description, date;
	private RatingBar rating;
	private ImageButton yesButton, noButton;
	
	// Animation
	private Animation animMiddleToOutRight;
	private Animation animOutLeftToMiddle;
	private boolean isFirstTime;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		placeName = (TextView) findViewById(R.id.surprise_me_place_name_tv);
		address = (TextView) findViewById(R.id.surprise_me_place_address_tv);
		description = (TextView) findViewById(R.id.surprise_me_place_description_tv);
		category = (ImageView) findViewById(R.id.surprise_me_place_category_tv);
		date = (TextView) findViewById(R.id.surprise_me_place_date_added_tv);
		rating = (RatingBar) findViewById(R.id.surprise_me_place_rating);
		
		yesButton = (ImageButton) findViewById(R.id.surprise_me_place_yes_button);
		yesButton.setOnClickListener(this);
		noButton = (ImageButton) findViewById(R.id.surprise_me_place_no_button);
		noButton.setOnClickListener(this);
		
		animMiddleToOutRight = AnimationUtils.loadAnimation(getApplicationContext(),
                R.anim.move_from_middle_to_out_right);
		animOutLeftToMiddle = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.move_from_out_left_to_middle);
		animMiddleToOutRight.setAnimationListener(this);
		// on the first time we do showNextPlace no need for animation
		isFirstTime = true;
		
		randomPlaces = new ArrayList<Place>(Places.getInstance().getAllPlaces());
		// if there are no places to show just tell the user and go back to home activity
		if(randomPlaces != null && randomPlaces.size() == 0){
			Toast.makeText(this, "Sorry, no places to show", Toast.LENGTH_SHORT).show();
			finish();
		}
		Collections.shuffle(randomPlaces);
		currIndex = 0;
		
		showNextPlace();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.surprise_me, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.action_surprise_me_done){
			finish();
			return true;
		} else 
			return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.surprise_me_place_yes_button:
				Intent intent = new Intent(SurpriseMeActivity.this, PlaceProfileActivity.class);
				ArrayList<Place> allPlaces = Places.getInstance().getAllPlaces();
				int realIndex = allPlaces.indexOf(randomPlaces.get(currIndex));
				Places.getInstance().setCurrentPlace(realIndex, 1);
				startActivity(intent);
				break;
			case R.id.surprise_me_place_no_button:
				if(currIndex == randomPlaces.size()-1){
					Toast.makeText(this, "Sorry, no more places around, try to increase the search radius",
							Toast.LENGTH_SHORT).show();
					finish();
				}
				else{
					currIndex++;
					showNextPlace();
				}
				break;
		}
	}
	
	
	private void showNextPlace(){
		// first place no need for animation

		if(isFirstTime){
			isFirstTime = false;
			placeName.setText(randomPlaces.get(currIndex).getName());
            String currAddress = randomPlaces.get(currIndex).getStreet() + ", " + 
                            randomPlaces.get(currIndex).getCity() + ", " + randomPlaces.get(currIndex).getCountry(); 
            address.setText(currAddress);
            description.setText(randomPlaces.get(currIndex).getDescription());
            date.setText(DateUtils.getRelativeTimeSpanString(randomPlaces.get(currIndex).getDate().getTime()));
            String categoryId = randomPlaces.get(currIndex).getCategory();
            category.setImageBitmap(BitmapFactory.decodeByteArray(Categories.getInstance().getCategoryById(categoryId).getImage(),0,Categories.getInstance().getCategoryById(categoryId).getImage().length));
            rating.setRating(randomPlaces.get(currIndex).getRating());
            
        // second place and on, start animation
		} else{
			placeName.startAnimation(animMiddleToOutRight);
			address.startAnimation(animMiddleToOutRight);
			rating.startAnimation(animMiddleToOutRight);
			category.startAnimation(animMiddleToOutRight);
			description.startAnimation(animMiddleToOutRight);
			date.startAnimation(animMiddleToOutRight);
		}
	}
	
	@Override
    protected void onNavItemSelected(int id) {
		Intent intent = null;
        switch ((int)id) {
        // Home nav button was pressed
        case 101:
        	intent = new Intent(this, HomeActivity.class);
            break;
        // My places nav drawer was pressed
        case 102:
        	intent = new Intent(this, MyPlacesNew.class);
        	break;
        // Settings nav button was pressed
        case 103:
            intent = new Intent(this, SettingsActivity.class);
            break;
	    }
        if(intent != null)
        	startActivity(intent);
        else
        	super.onNavItemSelected(id);
    }
	
	/*
     * Initialize the nav drawer configurations and returns it to navConf
     */
	@Override
    protected NavDrawerActivityConfiguration getNavDrawerConfiguration() {
        NavDrawerItem[] menu = new NavDrawerItem[] {
        		NavMenuFBHeader.create( 100, "User"),
                NavMenuItem.create(101, "Home", "ic_home", this),
                NavMenuItem.create(102, "My Places", "ic_menu_myplaces", this),
                NavMenuItem.create(103, "Settings", "ic_menu_settings", this),
                NavMenuItem.create(105, "About", "ic_action_about_light", this),
                NavMenuItem.create(107, "Rate Us!", "ic_whats_hot", this),
                NavMenuItem.create(108, "Logout", "ic_menu_logout", this)};
        
        NavDrawerActivityConfiguration navDrawerActivityConfiguration = new NavDrawerActivityConfiguration();
        navDrawerActivityConfiguration.setMainLayout(R.layout.activity_surprise_me);
        navDrawerActivityConfiguration.setDrawerLayoutId(R.id.drawer_layout);
        navDrawerActivityConfiguration.setLeftDrawerId(R.id.left_drawer);
        navDrawerActivityConfiguration.setNavItems(menu);
        navDrawerActivityConfiguration.setDrawerShadow(R.drawable.drawer_shadow);       
        navDrawerActivityConfiguration.setDrawerOpenDesc(R.string.drawer_open);
        navDrawerActivityConfiguration.setDrawerCloseDesc(R.string.drawer_close);
        navDrawerActivityConfiguration.setBaseAdapter(
            new NavDrawerAdapter(this, R.layout.navdrawer_item, menu ));
        return navDrawerActivityConfiguration;
    }

////////////////////////// ANIMATION ///////////////////////////////////////////////////////////////	
	
	@Override
	public void onAnimationEnd(Animation anim) {
		if(anim == animMiddleToOutRight){

			placeName.setText(randomPlaces.get(currIndex).getName());

			placeName.startAnimation(animOutLeftToMiddle);
			String currAddress = randomPlaces.get(currIndex).getStreet() + ", " + 
                    randomPlaces.get(currIndex).getCity() + ", " + randomPlaces.get(currIndex).getCountry(); 
			address.setText(currAddress);
			address.startAnimation(animOutLeftToMiddle);
			rating.setRating(randomPlaces.get(currIndex).getRating());
			rating.startAnimation(animOutLeftToMiddle);
			String categoryId = randomPlaces.get(currIndex).getCategory();
			category.setImageBitmap(BitmapFactory.decodeByteArray(Categories.getInstance().getCategoryById(categoryId).getImage(),0,Categories.getInstance().getCategoryById(categoryId).getImage().length));
            category.startAnimation(animOutLeftToMiddle);

			description.setText(randomPlaces.get(currIndex).getDescription());
			description.startAnimation(animOutLeftToMiddle);

			date.setText(DateUtils.getRelativeTimeSpanString(randomPlaces.get(currIndex).getDate().getTime()));
			date.startAnimation(animOutLeftToMiddle);
		}
	}

	@Override
	public void onAnimationRepeat(Animation animation) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onAnimationStart(Animation animation) {
		// TODO Auto-generated method stub
		
	}
}
